package com.firstgroup.dms.service.impl;

import com.firstgroup.dms.mapper.SaleMapper;

import com.firstgroup.dms.pojo.Sale;

import com.firstgroup.dms.service.SaleService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

import java.util.Random;

import java.text.SimpleDateFormat;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

@Service

public class SaleServiceImpl implements SaleService {

    @Autowired

    private SaleMapper saleMapper;

    @Override

    public List<Sale> getAllSales() {

        return saleMapper.getAllSales();

    }

    @Override

    @Transactional
    public boolean deleteSale(Integer id) {

        // 1. 先删除销售明细
        saleMapper.deleteSaleDetail(id);
        // 2. 再删除销售单
        return saleMapper.deleteSale(id) > 0;

    }

    @Override

    @Transactional
    public void addSale(Sale sale) {
        // 生成销售单号
        if (sale.getOrderNo() == null || sale.getOrderNo().isEmpty()) {
            String orderNo = generateOrderNo();
            sale.setOrderNo(orderNo);
        }

        // 1. 保存销售单主表
        saleMapper.insertSale(sale);

        // 2. 保存销售明细
        if (sale.getDetails() != null && !sale.getDetails().isEmpty()) {
            sale.getDetails().forEach(detail -> {
                detail.setSaleId(sale.getId()); // 设置销售单ID
                saleMapper.insertSaleDetail(detail);
            });
        }
    }

    private String generateOrderNo() {

        // 生成销售单号：XS + 年月日 + 3位随机数

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        String dateStr = sdf.format(new Date());

        String randomStr = String.format("%03d", new Random().nextInt(1000));

        return "XS" + dateStr + randomStr;

    }

}